package com.moss.cloud.common.security.interceptor;

import com.moss.cloud.auth.api.utils.JwtAccessToken;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.custom.CustomHttpHeaders;
import com.moss.cloud.common.core.model.vo.AuthUser;
import com.moss.cloud.common.core.utils.AuthUserUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户信息拦截器
 *
 * @author 瑾年
 * @date 2023年3月14日
 */
@Slf4j
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) {
        String authorization = StringUtils.defaultIfBlank(request.getHeader(CustomHttpHeaders.X_CLIENT_TOKEN_USER), Constant.NO_LOGIN);
        log.info("原始认证用户信息:{}", authorization);
        if (StringUtils.isNotBlank(authorization) && !authorization.equals(Constant.NO_LOGIN)) {
            String userInfo = JwtAccessToken.getJwt(authorization).getClaims();
            AuthUser authUser = AuthUserUtil.preAuthUser(userInfo);
            log.info("当前登录用户:{}", authUser.getUserName());
            UserContextHolder.setUserInfo(authUser);
        } else {
            AuthUser authUser = AuthUserUtil.preAuthUser();
            log.info("用户未认证状态:{}", authUser.getAuthStatus());
            UserContextHolder.setUserInfo(authUser);
        }
        return true;
    }

    @Override
    public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) {
        UserContextHolder.clear();
    }
}
